<template>
  <div class="main_conntainer" :style="{backgroundImage:`url(${bgImg})`}" @click="getMouseXY($event)">
     <div class="container">
        <el-button type="primary" icon="el-icon-thumb" circle @click="showPictures" style="margin-bottom:10px"></el-button>
        <transition name="fade">
          <div v-if="show" class="pictures">
            <!-- <img src="./image1.png" alt="picture1">
            <img src="./image2.png" alt="picture2">
            <img src="./image3.png" alt="picture3"> -->

             <el-button type="primary" size="small" round  @click="PageOneFm">页面1</el-button>
             <el-button type="primary" size="small" round style="margin-top:10px" @click="PageTwoFm">页面2</el-button>
             <el-button type="primary" size="small" round style="margin-top:10px" @click="PageSanFm">页面3</el-button>

          </div>
        </transition>
     </div>

  </div>
</template>

<script>
import protoRoot from "@/proto/proto.js";
export default {
  data() {
    return {
       bgImg:"./picOne.png",
      show: false,  // 是否显示图片
      // websocket相关
      socketObj: "", // websocket实例对象
      //心跳检测
      heartCheck: {
        vueThis: this, // vue实例
        timeout: 10000, // 超时时间
        timeoutObj: null, // 计时器对象——向后端发送心跳检测
        serverTimeoutObj: null, // 计时器对象——等待后端心跳检测的回复
        // 心跳检测重置
        reset: function () {
          clearTimeout(this.timeoutObj);
          clearTimeout(this.serverTimeoutObj);
          return this;
        },
        // 心跳检测启动
        start: function () {
          this.timeoutObj && clearTimeout(this.timeoutObj);
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
          this.timeoutObj = setTimeout(() => {
            //  console.log("发送心跳检测");
            //   console.log(this);
            //   console.log(this.vueThis);
            //   console.log("发送心跳检测");
            // 这里向后端发送一个心跳检测，后端收到后，会返回一个心跳回复
             let  dataData = protoRoot.lookup("protocol.Tick");
            let  dataDataOne=  dataData.create({ userId: 'BeiJing1-2',  });
            let  bufferData = dataData.encode(dataDataOne).finish();
            var arrayArr = Array.from(bufferData)
            let btyeData= this.vueThis.IntToBytesLittleEndian(0,4)  
            let twoDataCommit=[...btyeData,...arrayArr]
            let btyeDatTwo=new Uint8Array(twoDataCommit).buffer
            // this.vueThis.socketObj.send("HeartBeat");
            this.vueThis.socketObj.send(btyeDatTwo);

            console.log("发送心跳检测");
            this.serverTimeoutObj = setTimeout(() => {
              // 如果超过一定时间还没重置计时器，说明websocket与后端断开了
              console.log("未收到心跳检测回复");
              // 关闭WebSocket
              this.vueThis.socketObj.close();
            }, 40000);

          }, this.timeout);

        },
      },
      socketReconnectTimer: null, // 计时器对象——重连
      socketReconnectLock: false, // WebSocket重连的锁
      socketLeaveFlag: false, // 离开标记（解决 退出登录再登录 时出现的 多次相同推送 问题，出现的本质是多次建立了WebSocket连接）

    };
  },
  created() {
    console.log("离开标记", this.socketLeaveFlag);
  },
  mounted() {
    // websocket启动
    this.createWebSocket();
  },
  destroyed() {
    // 离开标记
    this.socketLeaveFlag = true;
    // 关闭WebSocket
    this.socketObj.close();
  },
  methods: {
     getMouseXY(e){
        console.log(e.pageX )
         console.log(e.pageY  )
     },
     showPictures() {
      this.show = !this.show;  // 点击按钮后切换show的值，实现显隐效果
    },
    
     PageOneFm(){
      this.bgImg ="./picOne.png"; 
      let  dataData = protoRoot.lookup("protocol.Move");
     let  dataDataOne=  dataData.create({ x: 400, audio: "1",  });
     let  bufferData = dataData.encode(dataDataOne).finish();
     var arrayArr = Array.from(bufferData)
    let btyeData= this.IntToBytesLittleEndian(3,4)  
    let twoDataCommit=[...btyeData,...arrayArr]
    let btyeDatTwo=new Uint8Array(twoDataCommit).buffer
     console.log('mmmmmmmmmmmmmm')
     console.log(bufferData)
     console.log(arrayArr)
     console.log(btyeData)
     console.log(btyeDatTwo)
     console.log('mmmmmmmmmmmmmmmmm')
    
     this.onsendCallback( btyeDatTwo );

    },
    PageTwoFm(){
     this.bgImg ="./picTwo.png";
      let  dataData = protoRoot.lookup("protocol.Move");
     let  dataDataOne=  dataData.create({ x: -400, audio: "2",  });
     let  bufferData = dataData.encode(dataDataOne).finish();
     var arrayArr = Array.from(bufferData)
    let btyeData= this.IntToBytesLittleEndian(3,4)  
    let twoDataCommit=[...btyeData,...arrayArr]
    let btyeDatTwo=new Uint8Array(twoDataCommit).buffer
     console.log('222222222222222222')
     console.log(bufferData)
     console.log(arrayArr)
     console.log(btyeData)
     console.log(btyeDatTwo)
     console.log('222222222222222222222')
     this.onsendCallback( btyeDatTwo );

    },
     PageSanFm(){
     this.bgImg ="./picSan.png";
      let  dataData = protoRoot.lookup("protocol.Move");
     let  dataDataOne=  dataData.create({ x: 400, audio: "3",  });
     let  bufferData = dataData.encode(dataDataOne).finish();
     var arrayArr = Array.from(bufferData)
    let btyeData= this.IntToBytesLittleEndian(3,4)  
    let twoDataCommit=[...btyeData,...arrayArr]
    let btyeDatTwo=new Uint8Array(twoDataCommit).buffer
     console.log('222222222222222222')
     console.log(bufferData)
     console.log(arrayArr)
     console.log(btyeData)
     console.log(btyeDatTwo)
     console.log('222222222222222222222')
     this.onsendCallback( btyeDatTwo );
    },
    // websocket启动
    createWebSocket() {
      let webSocketLink = "ws://123.249.69.100:9090"; // webSocket地址
      // console.log(webSocketLink);
      try {
        if ("WebSocket" in window) {
          this.socketObj = new WebSocket(webSocketLink);
        } else if ("MozWebSocket" in window) {
          this.socketObj = new MozWebSocket(webSocketLink);
        }
        this.socketObj.binaryType = 'arraybuffer'
        // websocket事件绑定
        this.socketEventBind();
      } catch (e) {
        console.log("catch" + e);
        // websocket重连
        this.socketReconnect();
      }
    },
    // websocket事件绑定
    socketEventBind() {
      // 连接成功建立的回调
      this.socketObj.onopen = this.onopenCallback;
      // 连接发生错误的回调
      this.socketObj.onerror = this.onerrorCallback;
      // 连接关闭的回调
      this.socketObj.onclose = this.oncloseCallback;
      // 向后端发送数据的回调
      this.socketObj.onsend = this.onsendCallback;
      // 接收到消息的回调
      this.socketObj.onmessage = this.getMessageCallback;

      //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = () => {
        this.socketObj.close();
      };
    },
    // websocket重连
    socketReconnect() {
      if (this.socketReconnectLock) {
        return;
      }
      this.socketReconnectLock = true;
      this.socketReconnectTimer && clearTimeout(this.socketReconnectTimer);
      this.socketReconnectTimer = setTimeout(() => {
        console.log("WebSocket:重连中...");
        this.socketReconnectLock = false;
        // websocket启动
        this.createWebSocket();
      }, 4000);
    },
    // 连接成功建立的回调
    onopenCallback: function (event) {
      console.log("WebSocket:已连接");
      // 心跳检测重置
       console.log("socket连接成功")
        let  dataData = protoRoot.lookup("protocol.Login");
        let  dataDataOne=  dataData.create({ userId: 'BeiJing1-2', password: "1111",  });
        let  bufferData = dataData.encode(dataDataOne).finish();
        var arrayArr = Array.from(bufferData)
        let btyeData= this.IntToBytesLittleEndian(1,4)  
        let twoDataCommit=[...btyeData,...arrayArr]
        let btyeDatTwo=new Uint8Array(twoDataCommit).buffer
        console.log('MoveParm MoveParm')
        console.log(bufferData)
        console.log(arrayArr)
        console.log(btyeData)
        console.log(btyeDatTwo)
        console.log('MoveParm MoveParm')
        this.onsendCallback(btyeDatTwo)
      this.heartCheck.reset().start();
    },
    // 连接发生错误的回调
    onerrorCallback: function (event) {
      console.log("WebSocket:发生错误");
      // websocket重连
      this.socketReconnect();
    },
    // 连接关闭的回调
    oncloseCallback: function (event) {
      console.log("WebSocket:已关闭");
      // 心跳检测重置
      this.heartCheck.reset();
      if (!this.socketLeaveFlag) {
        // 没有离开——重连
        // websocket重连
        this.socketReconnect();
      }
    },
    // 向后端发送数据的回调
    onsendCallback: function (Data) {
      console.log("WebSocket:发送信息给后端");
       this.socketObj.send(Data);
    },
   IntToBytesLittleEndian(number, length){
        var bytes = [];
        var i = 0;
        do {
        bytes[i++] = number & (255);
        number = number>>8;
        } while ( i < length )
        return bytes;
    },
    // 接收到消息的回调
    getMessageCallback: function (data) {
      
     
      const dataJson = data
      const bf = dataJson.data;
      const newStart = bf.slice(0, 4); // 从0 - 9 不包括 10
      const newBEnd = bf.slice(4, 8); // 从0 - 9 不包括 10

      const uIntStart = new Uint8Array(newStart)
      var arrayStart = Array.from(uIntStart)
      const uIntEnd = new Uint8Array(newBEnd)
     
      //登录
      if(arrayStart.toString()==[2,0,0,0].toString()){
           let  dataData = protoRoot.lookup("protocol.LoginEnd");
           console.log( 'qqqqqqqqqqqqqqqqqqq' )
           console.log(dataData.decode(uIntEnd))
             console.log( 'qqqqqqqqqqqqqqqqqqq' )
      }else if( arrayStart.toString()==[0,0,0,0].toString() ) {
          //  console.log(dataData.decode(uIntEnd))
          this.heartCheck.reset().start();
      }
       console.log( ' sucess sucess sucess' )
       console.log( dataJson )
       console.log(uIntStart)
       console.log(arrayStart)
       console.log(dataJson)
       console.log( ' sucess sucess sucess' )

      // if (msg.data.indexOf("HeartBeat") > -1) {
      //   // 心跳回复——心跳检测重置
      //   // 收到心跳检测回复就说明连接正常
      //   console.log("收到心跳检测回复");
      //   // 心跳检测重置
      //   this.heartCheck.reset().start();
      // } else {
      //   // 普通推送——正常处理
      //   console.log("收到推送消息");
      //   let data = JSON.parse(msg.data);
      //   // 相关处理
      //   console.log(data);
      // }

    },
  },
};
</script>

<style scoped>
.main_conntainer{
  padding:8px;
  width: 100%;
  height:90vh;
  background-size: 100%;
  background-repeat: no-repeat;

}
.container {

}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.6s;
}

.fade-enter, .fade-leave-to {
  opacity:0.6 ;
}

.pictures {
  display: flex;
  flex-direction: column;
 align-items: baseline;
  /* display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center; */
}

.pictures img {
  max-width: 100%;
  margin: 10px;
  /* position: ab; */
}
</style>